// 引入接口文件
import { addFun, editFun, queryInfo, findProduct, initQueryField, addlittle, findByInformation, uploadImage } from './competingGoodsDetailServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
import { rstr2b64 } from '../../../../utils/md5'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import config from 'config/config'

const queryList = [
  {
    name: '区域', type: 'selectClear', key: 'areaId', value: '', notNeedAll: true, list: []
  },
  {
    name: '项目', type: 'selectClear', key: 'projectId', value: '', notNeedAll: true, list: []
  },
  {
    name: '状态', type: 'selectClear', key: 'state', value: '', notNeedAll: true, list: [
      { id: '1', name: '已关联' },
      { id: '0', name: '未关联' }
    ]
  }
]
// 初始默认状态
const defultState = {
  btnLoading: false,
  mapList: [],
  mapListShow: false,
  tableObj: {
    key: '',
    areaInterval: '',
    houseAmount: '',
    image: '',
    houseStaus: '',
    area: '',
    productHouseType: '',
    productType: '',
  },
  queryList,
  tableData: [],
  totalTableData: [],
  competitorOpeningQuotationList: [],
  competitorOpeningQuotationItem: {
    openingTime: '',
    openingPi: '',
    openingMethod: '',
    productType: '',
    productHouseType: '',
    area: '',
    openingPrice: '',
    openingOffer: '',
    totalSubscription: '',
    totalVolume: '',
    totalValue: '',
    removalSetNum: '',
    removalRate: '',
    openingEffect: '',
    competitorOpeningSalesAnalysis: '',
    marketTrendJudgment: '',
    parentCode: '',
  },
  parentCode: 0,
  goods: [],
  areaList: [],
  products: [],
  productList: [],
  attributeList: [],
  loading: false,
  keys: 0,
  actionType: 'add',
  pModalObj: {
    visible: false
  },
  brandNameModal: {
    visible: false
  },
  imgModal: {
    visible: false
  },
  url: '',
  newProduct: '',
  mapVisible: false,
  address: "",
  latAndLon: ['', ''],
  productTypeList: [],
  selectedProject: '',
  productId: '',
  query: {
    id: '',
    // brandName: '',//竞品品牌
    // address: '',//地址
    // competingGoodsName: '',//竞品名称
    // competingGoodsType: '',//竞品类型
    // isSale: '',//竞品状态
    // plotRatio: '',//容积率
    // floorSpace: '',//占地面积
    // relationProject: '',//关联我司项目
    attributeItem: {
      tableName: '竞品管理',
      itemValue: ''
    },
    productList: [],
    competitorOpeningQuotationList: [],
  },
  suitableDataList: {
    dataSource: [],
    total: 0,
    stop: 0,
    start: 0
  },
  // 表格分页设置
  pageConfig: {
    pageSize: Number.parseInt(config.smallPageSizeList[0]),
    pageNo: 1
  },
  downId: null,
}

// 声明module
const tmpModule = {
  namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          dispatch({ type: 'findProduct', payload: {} })
          if (query.actionType == 'check' || query.actionType == 'edit') {
            dispatch({ type: 'queryInfo', payload: { id: query.id } })
          }
          dispatch({ type: 'getFieldFun', payload: {} })
          dispatch({ type: 'initQueryField', payload: {} })
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    *queryInfo({ payload }, { put, select, call }) {
      let { tableData, attributeList, query, selectedProject, address, mapVisible, latAndLon, competitorOpeningQuotationList, parentCode, downId } = yield select(state => state[tmpModule.namespace])
      let params = {
        id: payload.id,
      }
      downId = payload.id;
      const { success, msg, result } = yield call(queryInfo, { ...params })
      attributeList = JSON.parse(result.attributeItem.itemValue)
      for (var item of attributeList) {
        if (item.attributeName == "竞品周报录入授权项目") {
          selectedProject = item.itemContent
        }
        if (item.attributeName == "首次开盘时间") {
          item.tableField = "openTime"
        }
      }
      latAndLon[0] = Number(result.lat)
      latAndLon[1] = Number(result.lng)
      tableData = result.productList;
      query = result;
      address = result.address;
      mapVisible = true;
      for (let item of result.competitorOpeningQuotationList) {
        // item.openingTime ? (item.openingTime = moment(item.openingTime, 'YYYY-MM-DD')) : null;
        parentCode = item.parentCode;
      }
      competitorOpeningQuotationList = result.competitorOpeningQuotationList;
      for(let item of competitorOpeningQuotationList) {
        item.area += '';
        item.openingPrice += '';
        item.totalSubscription += '';
        item.totalVolume += '';
        item.totalValue += '';
        item.removalSetNum += '';
      }
      yield put({ type: 'updateStore', payload: { downId, tableData, attributeList, query, selectedProject, address, mapVisible, latAndLon, competitorOpeningQuotationList, parentCode } })
      yield put({ type: 'findByInformation', payload: { id: payload.id } })
    },
    *getFieldFun({ payload }, { put, select, call }) {
      let { attributeList, productTypeList, actionType } = yield select(state => state[tmpModule.namespace])
      let params = {
        projectId: 'E91689C4-0601-44FC-AAB3-337882C70FFE',
      }
      const { success, msg, productType, attribute } = yield call(editFun, { ...params })
      productTypeList = productType
      if (actionType == 'add') {
        attributeList = attribute
        yield put({ type: 'updateStore', payload: { attributeList } })
      }
      yield put({ type: 'updateStore', payload: { productTypeList } })
    },
    *initQueryField({ payload }, { put, select, call }) {
      let { goods } = yield select(state => state[tmpModule.namespace])
      let params = {
        projectId: 'E91689C4-0601-44FC-AAB3-337882C70FFE',
      }
      const { success, msg, competingGoods } = yield call(initQueryField, { ...params })
      // if(success){
      goods = competingGoods
      yield put({ type: 'updateStore', payload: { goods } })
      // }
    },
    *findByInformation({ payload }, { put, select, call }) {
      let { totalTableData } = yield select(state => state[tmpModule.namespace])
      let params = {
        id: payload.id,
      }
      const { success, msg, result } = yield call(findByInformation, { ...params })
      if (success) {
        totalTableData = result
        yield put({ type: 'updateStore', payload: { totalTableData } })
      }
    },
    *addlittle({ payload }, { put, select, call }) {
      let params = {
        id: payload.id,
        itemContent: payload.itemContent
      }
      const { success } = yield call(addlittle, { ...params })
      if (success) { }
    },
    *findProduct({ payload }, { put, select, call }) {
      let { areaList, queryList, productList, attributeList } = yield select(state => state[tmpModule.namespace])
      let params = {
        userId: localStorage.username
      }
      const { success, msg, projectList } = yield call(findProduct, { ...params })
      // if(success){
      let list = projectList
      if (!list.length) {
        return
      }

      for (var itt of list) {
        for (var ptt of itt.projectList) {
          let obj = {
            areaId: itt.areaId,
            areaName: itt.areaName,
            projectId: ptt.projectId,
            projectName: ptt.projectName,
            state: 0
          }
          productList.push(obj)
        }
      }

      areaList = list.map((item, index) => {
        return {
          name: item.areaName,
          id: item.areaId,
          children: item.projectList
        }
      })
      queryList[0].list = areaList
      yield put({ type: 'updateStore', payload: { areaList, queryList, productList } })
      // }
    },
    //查询操作
    *search({ payload = {} }, { call, put, select }) {
      let { queryList, suitableDataList, productList } = yield select(state => state[tmpModule.namespace])
      //组装接口入参
      let params = {}
      params['areaId'] = queryList[0].value ? queryList[0].value : ''
      params['projectId'] = queryList[1].value ? queryList[1].value : ''
      params['state'] = queryList[2].value ? queryList[2].value : ''
      yield put({ type: 'updateStore', payload: { loading: true } })
      if (params.areaId) {
        suitableDataList.dataSource = productList.filter(item => item.areaId == params.areaId)
        if (params.projectId) {
          suitableDataList.dataSource = suitableDataList.dataSource.filter(item => item.projectId == params.projectId)
        }
        if (params.state) {
          suitableDataList.dataSource = suitableDataList.dataSource.filter(item => item.state == params.state)
        }
      } else {
        message.error('请先选择区域')
      }
      yield put({ type: 'updateStore', payload: { loading: false, suitableDataList } })
    },
    // 查询条件重置
    *queryReset({ }, { call, put, select }) {
      let { areaList, suitableDataList } = yield select(state => state[tmpModule.namespace])
      let newQueryList = cloneDeep(queryList)
      newQueryList[0].list = areaList
      suitableDataList.dataSource = []
      yield put({ type: 'updateStore', payload: { queryList: newQueryList, suitableDataList } });
    },

    //改变查询条件
    *inputChange({ payload }, { call, put, select }) {
      let { queryList } = yield select(state => state[tmpModule.namespace])
      const { key, value } = payload;
      let data = queryList.find(item => item.key === key);

      if (data.key == 'areaId') {
        yield put({ type: 'filterProjectList', payload: { areaId: value } })
      }
      data.value = value;
      //刷新列表参数
      yield put({ type: 'updateStore', payload: { queryList: [...queryList, ...data] } });
    },
    *upload({ payload }, { put, select, call }) {
      let { tableData } = yield select(state => state[tmpModule.namespace])
      let e = payload.e
      let file = e.target.files[0]
      let fileSize = (file.size) / 1024
      if (fileSize > 1024 * 2) {
        message.warn('文件大小不得超过 2M')
        return
      }
      let fileNameType = file.name.split('.').pop();
      let fileType = ['jpg', 'jpeg', 'png']
      if (fileType.indexOf(fileNameType) < 0) {
        message.warn('图片格式必须为 jpg 、jpeg、png')
        return
      }
      let fileInfo = new FormData()
      if (file) {
        fileInfo.append('file', file)
      }
      let params = {
        userId: localStorage.getItem('username'),
        file: fileInfo
      }
      let { success, url } = yield call(uploadImage, params)
      if (success) {
        for (var item of tableData) {
          if (item.key == payload.item.key) {
            item.image = url
          }
        }
        yield put({ type: 'updateStore', payload: { tableData } })
        message.success('上传成功')
      }
    },
    *submit({ payload }, { put, select, call }) {
      let { query, tableData, attributeList, btnLoading, competitorOpeningQuotationList } = yield select(state => state[tmpModule.namespace])
      query.attributeItem.itemValue = JSON.stringify(attributeList)
      query.productList = tableData
      if (!tableData.length) {
        message.warning('请先新增竞品产品信息')
        return
      }
      let list = attributeList.filter(item => !!item.tableField)
      for (var i = 0; i < list.length; i++) {
        query[list[i].tableField] = list[i].defaultValue
      }
      let temlist = attributeList.filter(item => item.attributeName == '竞品周报录入授权项目')[0].itemContent.split(',')
      for (var item of temlist) {
        if (item.split(':')[1] == query.projectId) {
          query.projectId = item.split(':')[0]
        }
      }
      for (let i = 0; i < competitorOpeningQuotationList.length; i++) {
        competitorOpeningQuotationList[i].sort = i + 1;
      }
      query.competitorOpeningQuotationList = competitorOpeningQuotationList;
      let params = query
      btnLoading = true
      yield put({ type: 'updateStore', payload: { btnLoading } })
      let { success} = yield call(addFun, { ...params })
      btnLoading = false;
      yield put({ type: 'updateStore', payload: { btnLoading } })
      if (success) {
        message.success('提交成功')
        hashHistory.push({
          pathname: '/home/predictManage/competingGoodsList',
          query: {}
        })
      }
    },
    *filterProjectList({ payload }, { put, select, call }) {
      let { products, areaList, queryList } = yield select(state => state[tmpModule.namespace])
      let list = []
      for (var item of areaList) {
        if (item.id == payload.areaId) {
          list = item.children
        }
      }
      if (list.length) {
        products = list.map((item, index) => {
          return {
            name: item.projectName,
            id: item.projectId,
          }
        })
      }
      queryList[1].list = products
      yield put({ type: 'updateStore', payload: { products, queryList } })
    },
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
